package com.ccit.realm;

import com.ccit.model.User;
import com.ccit.service.UserService;
import com.ccit.service.impl.UserRoleServiceImpl;
import com.ccit.service.impl.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class databaseRelalm extends AuthorizingRealm {

    @Autowired
    private UserService userServiceimpl;

     @Override
     public String getName(){
         return "databaseRelalm";
     }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String userName= token.getPrincipal().toString();
        String password= new String( t.getPassword());
        //获取数据库中的密码
        User user = userServiceimpl.login(userName);
        //如果为空就是账号不存在，如果不相同就是密码错误，但是都抛出AuthenticationException，而不是抛出具体错误原因，免得给破解者提供帮助信息
        if(null==user.getPassword() || !user.getPassword().equals(password))
            throw new AuthenticationException();
        //认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :databaseRealm
        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        return a;
    }
}
